package yadong.example.code;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class CleanExpiredEvents {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = null;
		HttpResponse response = null;
		BufferedReader rd  = null;
		int numberOfExpiredEvents = 2;
		String searchUrl = "http://www.washingtonpost.com/gog/search/q,group_Events,sortSpecifier_Date,docsPerPage_"+numberOfExpiredEvents+".html?showModels=searchView";
		request = new HttpGet(searchUrl);
		response = client.execute(request);
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));	
		String result = null;
		boolean printNextline = false;
		List<String> idList = new ArrayList<>();
		while ((result = rd.readLine()) != null) {
			if (printNextline){
				System.out.println(StringUtils.substringBetween(result, "<string>", "</string>"));
				idList.add(StringUtils.substringBetween(result, "<string>", "</string>"));
				printNextline = false;
			}
			if (result!=null&&result.startsWith("<string>egcontentid")){
				printNextline = true;
			}
		} 
		
		String url = null;
		for (String id : idList) {
			url = "http://glassadmin.digitalink.com/eidos-search-notifier/notify?operation=delete&app=GOG&url=http://glassadmin.digitalink.com/gogdocs/id/"+id+".xml";
			System.out.println(url);
			request = new HttpGet(url);
			response = client.execute(request);
			// Get the response
			rd = new BufferedReader
					(new InputStreamReader(response.getEntity().getContent()));		
			String rs = "";
			while ((rs = rd.readLine()) != null) {
				System.out.println("response:"+rs);
			} 
		}
	}

}
